<?php

class ProfileController extends FrontendController
{
	public $defaultAction = 'profile';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
	/**
	 * Shows a particular model.
	 */
	public function actionProfile()
	{
		/* $model = $this->loadUser();
	    $this->render('profile',array(
	    	'model'=>$model,
			'profile'=>$model->profile,
	    )); */
		$id = Yii::app()->user->id;
		$model = FrontendUsersAccountModel::model()->findByPk($id);
		$this->render('profile', array(
					'model'=>$model
				));
	}


	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionEdit()
	{
		$model = $this->loadUser();
		$profile=$model->profile;
		// ajax validator
		if(isset($_POST['ajax']) && $_POST['ajax']==='profile-form')
		{
			echo UActiveForm::validate(array($model,$profile));
			Yii::app()->end();
		}
		if(isset($_POST['FrontendUsersAccountModel']))
		{
			$model->attributes=$_POST['FrontendUsersAccountModel'];
			$profile->attributes=$_POST['Profile'];
			
			if($model->validateprofile()&&$profile->validate()) {
				$model->save();
				$profile->save();
                Yii::app()->user->updateSession();
				Yii::app()->user->setFlash('profileMessage',UserModule::t("Changes is saved."));
				$this->redirect(array('/user/profile/edit', array('id'=>Yii::app()->user->id)));
			} else $profile->validate();
		}

		$this->render('edit',array(
			'model'=>$model,
			'profile'=>$profile,
		));
	}
	
	/**
	 * Change password
	 */
	public function actionChangepassword() {
		$model = new UserChangePassword;
		if (Yii::app()->user->id) {
			
			// ajax validator
			if(isset($_POST['ajax']) && $_POST['ajax']==='changepassword-form')
			{
				echo UActiveForm::validate($model);
				Yii::app()->end();
			}
			
			if(isset($_POST['UserChangePassword'])) {
					$model->attributes=$_POST['UserChangePassword'];
					if($model->validate()) {
						$new_password = User::model()->notsafe()->findbyPk(Yii::app()->user->id);
						$new_password->password = UserModule::encrypting($model->password);
						$new_password->activkey=UserModule::encrypting(microtime().$model->password);
						$new_password->save();
						Yii::app()->user->setFlash('profileMessage',UserModule::t("New password is saved."));
						$this->redirect(array("profile"));
					}
			}
			$this->render('changepassword',array('model'=>$model));
	    }
	}
	public function actionDelimage()
	{
		$id = Yii::app()->request->getParam('id');
		$type = Yii::app()->request->getParam('type');
		$model = $this->loadUser();
		$avatar = $model->avatar;
		$model->avatar='';
		if($model->save()){
			$source = Yii::app()->params['storage_path'].'/profile/'.$model->id.'/source/'.$avatar;
			$thumb = Yii::app()->params['storage_path'].'/profile/'.$model->id.'/thumb/'.$avatar;
			@unlink($source);
			@unlink($thumb);
		}
		$data['error'] = false;
		echo CJSON::encode($data);
	}
	
	public function actionUpload()
	{
		if(isset($_POST['User'])){
			$id = $_POST['model_id'];
			$name = array_keys($_POST['User']);
			//get file type and check avaiable
				
			$file = $_FILES['User']['name']['avatar'];
			$file = utf8_decode($file);
			$file = preg_replace("/[^a-zA-Z0-9_.\-\[\]]/i", "", strtr($file, "()áàâãäéèêëíìîïóòôõöúùûüçÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ% ", "[]aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC__"));
			$file = strtolower($file);
			$filepath = pathinfo($file);
			$file_type_avaiable = $_POST['fileext'];
			$ext_file = $filepath['extension'];
			//check file type is avaiable?
			$fileTypes = str_replace('*.','',$file_type_avaiable);
			$fileTypes = str_replace(';','|',$fileTypes);
			$typesArray = split('\|',$fileTypes);
			if (!in_array($ext_file,$typesArray)) {
				echo 'error_file_type';
				Yii::app()->end();
			}else{
					
				$avatarUpload=CUploadedFile::getInstanceByName("User[avatar]");
	
				$image_name = time().'_'.$name[0].'.'.$ext_file;
				$dir = Yii::app()->params['storage_path'].'/profile/'.$id.'/source';
				if(is_dir($dir)==false){
					mkdir($dir, 0777, true);
				}
				if($avatarUpload->saveAs($dir.'/'.$image_name)){
					//resize
					if($_POST['autoresize']==true){
						$data = array();
						$image = Yii::app()->image->load($dir.'/'.$image_name);
						$image->resize(110, 110);
						$dirThumb = Yii::app()->params['storage_path'].'/profile/'.$id.'/thumb';
						if(is_dir($dirThumb)==false){
							mkdir($dirThumb, 0777, true);
						}
						$image->save($dirThumb.'/'.$image_name);
					}
					//update to db
					$model = $this->loadUser();
					if($model->avatar!=''){
						@unlink(Yii::app()->params['storage_path'].$model->avatar);
					}
					$model->avatar = $image_name;
					$model->save();
					echo Yii::app()->params['storage_url'].'/profile/'.$id.'/thumb/'.$image_name;
				}else{
					echo 'error_file_upload';
					Yii::app()->end();
				}
			}
		}
		Yii::app()->end();
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadUser()
	{
		if($this->_model===null)
		{
			if(Yii::app()->user->id)
				$this->_model=FrontendUsersAccountModel::model()->findByPk(Yii::app()->user->id);
			if($this->_model===null)
				$this->redirect(Yii::app()->controller->module->loginUrl);
		}
		return $this->_model;
	}
}